package com.neusoft.admin.controller;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.HashMap;
import java.util.Map;

import com.neusoft.admin.entity.AQIconfirmData;
import com.neusoft.grid.entity.Grid;
import com.neusoft.admin.method.GetColor;

import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.geometry.Pos;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.DatePicker;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.stage.Stage;

public class AQIconfirmListViewControl {
    @FXML
    private ObservableList<AQIconfirmData> dataList = FXCollections.observableArrayList();
    @FXML
    private TableView<AQIconfirmData> tableView;
    @FXML
    private TableColumn<AQIconfirmData, String> idColumn, provinceColumn, cityColumn, gradeColumn, dateColumn,
            timeColumn, gridColumn, nameColumn;
    @FXML
    private TableColumn<AQIconfirmData, Void> actionColumn;
    @FXML
    private ComboBox<String> provinceComboBox, cityComboBox;
    @FXML
    private Button clearButton;
    @FXML
    private DatePicker datePicker;
    private String ComboBoxStyle = "-fx-background-color: transparent; -fx-border-color:#DEE1E8; -fx-border-width: 1px; -fx-border-radius: 5px;";
    private AQIconfirmData AQIconfirmData;
    private String id, province, city, grade, date, time, gird, name;
    private Map<String, AQIconfirmData> map = new HashMap<>();

    @FXML
    public void initialize() {
        ObservableList<String> provinceList = FXCollections.observableArrayList("全部", "北京市", "辽宁省", "广东");
        provinceComboBox.setItems(provinceList);
        provinceComboBox.setStyle(ComboBoxStyle);
        ObservableList<String> cityList = FXCollections.observableArrayList("全部");
        cityComboBox.setItems(cityList);
        cityComboBox.setStyle(ComboBoxStyle);
        // 将数据添加到 TableView 中
        read();

        setupColumn(idColumn, "id");
        setupColumn(provinceColumn, "province");
        setupColumn(cityColumn, "city");
        setGrade(gradeColumn, "grade");
        setupColumn(dateColumn, "date");
        setupColumn(timeColumn, "time");
        setupColumn(gridColumn, "gird");
        setupColumn(nameColumn, "name");

        tableView.setItems(dataList);
        idColumn.setSortable(false);
        provinceColumn.setSortable(false);
        cityColumn.setSortable(false);
        actionColumn.setSortable(false);
        gradeColumn.setSortable(false);
        dateColumn.setSortable(false);
        timeColumn.setSortable(false);
        gridColumn.setSortable(false);
        nameColumn.setSortable(false);
        provinceComboBox.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> {
            if (newValue != null) {
                System.out.println("选择的省区域: " + newValue);
                // 根据选择的省区域更新市区域ComboBox的内容
                if ("广东".equals(newValue)) {
                    cityComboBox.setItems(FXCollections.observableArrayList("全部", "广州", "深圳", "珠海"));
                } else if ("北京市".equals(newValue)) {
                    cityComboBox.setItems(FXCollections.observableArrayList("全部", "北京市"));
                } else if ("辽宁省".equals(newValue)) {
                    cityComboBox.setItems(FXCollections.observableArrayList("全部", "沈阳市", "大连市"));
                }
                search();
            }
        });
        // 为市区域ComboBox添加选择事件处理
        cityComboBox.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> {
            if (newValue != null) {
                System.out.println("选择的市区域: " + newValue);
                search();
            }
        });
        datePicker.setStyle(ComboBoxStyle);
        datePicker.setOnAction(e -> {
            search();
        });
        clearButton.setOnAction(e -> {
            provinceComboBox.getSelectionModel().clearSelection();
            cityComboBox.getSelectionModel().clearSelection();
            datePicker.setValue(null);
            search();
        });
        actionColumn.setCellFactory(cols -> new TableCell<>() {
            private Button btn = new Button("查看详情");
            {
                btn.setStyle("-fx-background-color: #3d90fd; -fx-text-fill: white;-fx-background-radius: 5px;");
                btn.setOnAction(_ -> {
                    AQIconfirmData data = getTableView().getItems().get(getIndex());
                    try {
                        Stage stage = new Stage();
                        stage.setTitle("AQI确认详情");
                        // 加载 FXML 文件
                        FXMLLoader loader = new FXMLLoader(
                                getClass().getResource("/com/neusoft/admin/view/AQIconfirmView.fxml"));
                        // 创建控制器实例并传入参数
                        AQIconfirmViewControl controller = new AQIconfirmViewControl(data.getId(), data.getGird());
                        // 设置控制器
                        loader.setController(controller);
                        // 加载 FXML 内容
                        Parent root = loader.load();
                        stage.setScene(new Scene(root));
                        stage.show();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                });
            }

            @Override
            protected void updateItem(Void item, boolean empty) {
                super.updateItem(item, empty);
                setAlignment(Pos.CENTER); // 设置按钮居中对齐
                if (empty) {
                    setGraphic(null);
                } else {
                    setGraphic(btn);
                }
            }
        });
    }

    public void read() {
        File file = new File("src/com/neusoft/admin/data/mission.txt");
        Map<String, Grid> gridMap = readMapFromFile("src/com/neusoft/grid/data/grid.txt");
        try (BufferedReader br = new BufferedReader(new FileReader(file))) {
            if (!file.exists()) {
                System.out.println("文件不存在");
                return;
            }
            String line;
            int i = 1;
            while ((line = br.readLine()) != null) {
                String[] parts = line.split(" ");
                id = parts[0];
                name = parts[2];
                int spaceIndex = parts[6].indexOf("省");
                if (spaceIndex != -1) {
                    province = parts[6].substring(0, spaceIndex+1);
                } else {
                    province = parts[6];
                }
                int cityIndex = parts[7].indexOf("市");
                if (cityIndex != -1) {
                    if (spaceIndex != -1) {
                        city = parts[7].substring(0, cityIndex + 1);
                    } else {
                        city = parts[7];
                    }
                } else {
                    city = parts[7];
                }
                grade = parts[11];
                int yearIndex=parts[15].indexOf("年");
                int monthIndex=parts[15].indexOf("月");
                int dayIndex=parts[15].indexOf("日");

                String yearValue = parts[15].substring(0,yearIndex);
                int monthValue = Integer.parseInt(parts[15].substring(yearIndex+1,monthIndex));
                int dayValue = Integer.parseInt(parts[15].substring(monthIndex+1,dayIndex));
                if (monthValue < 10) {
                    date = yearValue + "-0" + monthValue + "-";
                    if (dayValue < 10) {
                        date += "0" + dayValue;
                    } else {
                        date += dayValue;
                    }

                } else {
                    date = yearValue + "-" + monthValue + "-";
                    if (dayValue < 10) {
                        date += "0" + dayValue;
                    } else {
                        date += dayValue;
                    }
                }
                time = "";
                gird = gridMap.get("1").getName();
                String isAssign=parts[16];
                if(isAssign.equals("已指派")){
                    map.put(id, new AQIconfirmData(id, province, city, grade, date, time, gird, name));
                }
                i++;
            }
            dataList.addAll(map.values());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public Map<String, Grid> readMapFromFile(String fileName) {
        Map<String, Grid> map = new HashMap<>();
        File file = new File(fileName);
        try {
            if (file.length() == 0) {
                map = new HashMap<>();
            } else {
                FileInputStream fis = new FileInputStream(file);
                ObjectInputStream ois = new ObjectInputStream(fis);
                map = (Map) ois.readObject();
                ois.close();
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return map;
    }

    public void search() {
        // 获取用户选择的筛选条件
        String selectedProvince = provinceComboBox.getValue();
        String selectedCity = cityComboBox.getValue();
        String selectedDate = datePicker.getValue() != null ? datePicker.getValue().toString() : null;

        // 创建一个新的列表来存储筛选后的数据
        ObservableList<AQIconfirmData> filteredList = FXCollections.observableArrayList();

        // 遍历原始数据列表
        for (AQIconfirmData data : dataList) {
            boolean matchProvince = true;
            boolean matchCity = true;
            boolean matchDate = true;
            // 检查日期条件
            if (selectedDate != null && !selectedDate.isEmpty() && !selectedDate.equals("全部")) {
                matchDate = data.getDate().equals(selectedDate);
            } else {
                matchDate = true; // 如果没有选择日期，则不进行筛选
            }
            // 检查省份条件
            if (selectedProvince != null && !selectedProvince.isEmpty() && !selectedProvince.equals("全部")) {
                matchProvince = data.getProvince().equals(selectedProvince);
            }

            // 检查城市条件
            if (selectedCity != null && !selectedCity.isEmpty() && !selectedCity.equals("请选择省区域")
                    && !selectedCity.equals("全部")) {
                matchCity = data.getCity().equals(selectedCity);
            }

            // 如果所有条件都匹配，则将数据添加到筛选列表中
            if (matchProvince && matchCity && matchDate) {
                filteredList.add(data);
            }
        }

        // 将筛选后的数据设置到 TableView 中
        tableView.setItems(filteredList);
        tableView.refresh();
        // 打印搜索条件
        System.out.println("搜索条件: 省区域=" + selectedProvince + ", 市区域=" + selectedCity +
                ", 日期=" + selectedDate);
    }

    private <T> void setupColumn(TableColumn<AQIconfirmData, T> column, String property) {
        column.setCellValueFactory(new PropertyValueFactory<>(property));
        column.setCellFactory(col -> new TableCell<>() {
            @Override
            protected void updateItem(T item, boolean empty) {
                super.updateItem(item, empty);
                if (empty || item == null) {
                    setText(null);
                } else {
                    setText(item.toString());
                }
                // 设置单元格内容居中显示
                setAlignment(Pos.CENTER);
            }
        });
    }

    public void setGrade(TableColumn<AQIconfirmData, String> column, String property) {
        column.setCellValueFactory(new PropertyValueFactory<>(property));
        column.setCellFactory(col -> new TableCell<>() {
            @Override
            protected void updateItem(String grade, boolean empty) {
                super.updateItem(grade, empty);
                if (empty || grade == null) {
                    setText(null);
                    setStyle("");
                } else {
                    setText(grade);
                    setAlignment(Pos.CENTER);
                    // 根据等级设置背景颜色
                    String gradeColor = GetColor.getColor(grade);
                    setStyle(gradeColor);
                }
            }
        });
    }

}